import os
import shutil
import docx
import re
import logging
from tqdm import tqdm
import win32com.client
import pythoncom
import tempfile

def convert_doc_to_docx(doc_path):
    """将.doc格式转换为.docx格式"""
    word = None
    try:
        pythoncom.CoInitialize()
        word = win32com.client.Dispatch("Word.Application")
        word.Visible = False
        temp_dir = tempfile.gettempdir()
        docx_path = os.path.join(temp_dir, os.path.basename(doc_path) + "x")
        doc = word.Documents.Open(doc_path)
        doc.SaveAs2(docx_path, FileFormat=16)
        doc.Close()
        return docx_path
    except Exception as e:
        logging.error(f"转换文档 {doc_path} 时出错: {str(e)}")
        return None
    finally:
        try:
            if word:
                word.Quit()
        except:
            pass
        pythoncom.CoUninitialize()

def has_violation_subtitle(doc):
    """
    判断"侵害用户权益"或"用户权益"章节是否包含子标题。
    章节编号可以是任意数字。
    """
    paragraphs = list(doc.paragraphs)
    for i, para in enumerate(paragraphs):
        if "（三）侵害用户权益问题：" in para.text:
            # Check the next paragraph if it exists
            if i + 1 < len(paragraphs):
                next_para = paragraphs[i + 1]
                if next_para.text.strip() == "无":
                    return False  # No violation
            return True  # Violation exists
    return False  # Subtitle not found, assume no violation

def classify_reports(report_dir, passed_dir, failed_dir):
    """
    遍历报告目录，将文档按是否通过分类移动。
    """
    if not os.path.exists(passed_dir):
        os.makedirs(passed_dir)
    if not os.path.exists(failed_dir):
        os.makedirs(failed_dir)
    files = [f for f in os.listdir(report_dir) if f.endswith('.doc') or f.endswith('.docx')]
    for file in tqdm(files, desc="分类中"):
        src_path = os.path.join(report_dir, file)
        temp_file = None
        try:
            doc_path = src_path
            if src_path.endswith('.doc'):
                temp_file = convert_doc_to_docx(src_path)
                if not temp_file:
                    logging.error(f"无法转换文件 {src_path}")
                    continue
                doc_path = temp_file
            doc = docx.Document(doc_path)
            if has_violation_subtitle(doc):
                # 不通过
                dst_path = os.path.join(failed_dir, file)
                shutil.move(src_path, dst_path)
                logging.info(f"{file} -> 不通过")
            else:
                # 通过
                dst_path = os.path.join(passed_dir, file)
                shutil.move(src_path, dst_path)
                logging.info(f"{file} -> 通过")
        except Exception as e:
            logging.error(f"处理文件 {file} 出错: {e}")
        finally:
            if temp_file and os.path.exists(temp_file):
                try:
                    os.remove(temp_file)
                except:
                    pass

def main():
    logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
    report_dir = r"F:\apk20250917\report"
    passed_dir = r"F:\apk20250917\通过"
    failed_dir = r"F:\apk20250917\不通过"
    classify_reports(report_dir, passed_dir, failed_dir)
    print("分类完成！")

if __name__ == "__main__":
    main()
